/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mantechhelpdesk.bean;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import mantechhelpdesk.dao.ComplaintsDao;
import mantechhelpdesk.dao.DbConnection;
import mantechhelpdesk.dao.DepartmentsDao;
import mantechhelpdesk.dao.RolesDao;
import mantechhelpdesk.dao.UsersDao;
import mantechhelpdesk.entity.Complaints;
import mantechhelpdesk.entity.Departments;
import mantechhelpdesk.entity.Roles;
import mantechhelpdesk.entity.Users;

/**
 *
 * @author MANHDD
 */
public class UsersBean {

    private Users users = null;
    private Complaints complaints = null;
    private List<Users> usersList;
    private List<SelectItem> departmentsList;
    private DepartmentsDao departmentsDao;
    private List<SelectItem> rolesList;
    private RolesDao rolesDao;
    private UsersDao usersDao;
    private Connection conn;
    private Statement st;
    private ResultSet res;
    private String oldPwd;
    private String newPwd;
    private String newPwdConfirm;
    private String text;

    public String getOldPwd() {
        return oldPwd;
    }

    public void setOldPwd(String oldPwd) {
        this.oldPwd = oldPwd;
    }

    public String getNewPwd() {
        return newPwd;
    }

    public void setNewPwd(String newPwd) {
        this.newPwd = newPwd;
    }

    public String getNewPwdConfirm() {
        return newPwdConfirm;
    }

    public void setNewPwdConfirm(String newPwdConfirm) {
        this.newPwdConfirm = newPwdConfirm;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Users getUsers() {
        return users;
    }

    public void setUsers(Users users) {
        this.users = users;
    }

    public List<Users> getUsersList() {
        return usersList;
    }

    public List<SelectItem> getRolesList() {
        return rolesList;
    }

    public void setRolesList(List<SelectItem> rolesList) {
        this.rolesList = rolesList;
    }

    public void setUsersList(List<Users> usersList) {
        this.usersList = usersList;
    }

    public List<SelectItem> getDepartmentsList() {
        return departmentsList;
    }

    public Complaints getComplaints() {
        return complaints;
    }

    public void setComplaints(Complaints complaints) {
        this.complaints = complaints;
    }

    /**
     * Creates a new instance of UsersBean
     */
    public UsersBean() {
        try {
            users = new Users();
            complaints = new Complaints();
            rolesDao = new RolesDao();
            departmentsDao = new DepartmentsDao();
            usersDao = new UsersDao();
            conn = DbConnection.getConnection();
            usersList = usersDao.loadAll(conn);

            departmentsList = new ArrayList();
            List allDepart = departmentsDao.loadAll(conn);
            Iterator it = allDepart.iterator();
            while (it.hasNext()) {
                Departments departments = (Departments) it.next();
                departmentsList.add(new SelectItem(departments.getDepartmentID(), departments.getDepartmentName()));
            }

            rolesList = new ArrayList();
            List allRole = rolesDao.loadAll(conn);
            Iterator at = allRole.iterator();
            while (at.hasNext()) {
                Roles roles = (Roles) at.next();
                rolesList.add(new SelectItem(roles.getRoleID(), roles.getRoleName()));
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public String addNew() {
        FacesContext ct = FacesContext.getCurrentInstance();
        try {
            if (users.getUsername().length() > 0) {
                Calendar now = GregorianCalendar.getInstance();
                users.setCreateTime(now.getTime());
                usersDao.create(conn, users);
                usersList = usersDao.loadAll(conn);
                ct.addMessage("", new FacesMessage("User addnew Success!"));
            } else {
                ct.addMessage("", new FacesMessage("Required to input a User name!"));
                return "userAddError";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            ct.addMessage("", new FacesMessage("Cannot addnew User!"));
        }
        return "userAddBack";
    }
    
    public String addNewComplaint() {
        FacesContext ct = FacesContext.getCurrentInstance();
        try {
            if (complaints.getComplaintContent().length() > 0) {
                ComplaintsDao complaintsDao = new ComplaintsDao();
                Calendar now = GregorianCalendar.getInstance();
                complaints.setCreateTime(now.getTime());
                complaints.setFinishedTime(now.getTime());
                complaints.setHasReplied(false);
                complaints.setIsFinished(false);
                complaintsDao.create(conn, complaints);
                
                //Load data
                
                
                complaints = complaintsDao.getComplaintsByUserId(conn, complaints.getUserID());
                ct.addMessage("", new FacesMessage("Answer addnew Success!"));
            } else {
                ct.addMessage("", new FacesMessage("Required to input a Answer name!"));
                return "addNewError";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            ct.addMessage("", new FacesMessage("Cannot addnew Answer!"));
        }
        return "complaintAddBack";
    }

    public String update() {
        FacesContext ct = FacesContext.getCurrentInstance();
        try {
            if (users.getUsername().length() > 0) {
                usersDao.save(conn, users);
                usersList = usersDao.loadAll(conn);
                ct.addMessage("", new FacesMessage("User update Success!"));
            } else {
                ct.addMessage("", new FacesMessage("Required to input a User name!"));
                return "userUpdateError";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            ct.addMessage("", new FacesMessage("Cannot update User!"));
        }
        return "userUpdateBack";
    }

    public String delete() {
        FacesContext ct = FacesContext.getCurrentInstance();
        try {
            usersDao.delete(conn, users);
            ct.addMessage("", new FacesMessage("User delete Success!"));
            usersList = usersDao.loadAll(conn);
        } catch (Exception ex) {
            ex.printStackTrace();
            ct.addMessage("", new FacesMessage("Cannot delete User!"));
        }
        return "userDelBack";
    }

    public String prepareData4Update() {
        try {
            FacesContext ct = FacesContext.getCurrentInstance();
            Map<String, String> map = ct.getExternalContext().getRequestParameterMap();
            String id = map.get("idParam");
            users = usersDao.getObject(conn, Integer.parseInt(id));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "userUpdate";
    }
    
    public String prepareData4AddComplaint() {
        try {
            FacesContext ct = FacesContext.getCurrentInstance();
            Map<String, String> map = ct.getExternalContext().getRequestParameterMap();
            String id = map.get("idParam");
            users = usersDao.getObject(conn, Integer.parseInt(id));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "complaintAddNew";
    }
    
    public String prepareData4ComplaintView() {
        try {
            FacesContext ct = FacesContext.getCurrentInstance();
            Map<String, String> map = ct.getExternalContext().getRequestParameterMap();
            String id = map.get("idParam");
            users = usersDao.getObject(conn, Integer.parseInt(id));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "complaintList";
    }

    public String prepareData4ChangePass() {
        try {
            FacesContext ct = FacesContext.getCurrentInstance();
            Map<String, String> map = ct.getExternalContext().getRequestParameterMap();
            String id = map.get("idParam");
            users = usersDao.getObject(conn, Integer.parseInt(id));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "userChangePass";
    }

    public String changePassword() {
        FacesContext ct = FacesContext.getCurrentInstance();
        try {
            Map<String, String> map = ct.getExternalContext().getRequestParameterMap();
            String id = map.get("idParam");
            String query = "SELECT Password FROM Users where UserID='" + Integer.parseInt(id) + "'";
            st = conn.createStatement();
            res = st.executeQuery(query);

            boolean isPwdValid = false;
            if (res.next()) {
                isPwdValid = res.getString("Password").equals(getOldPwd());
            }
            if (isPwdValid) {
                if (newPwd.length() < 6 || newPwd.length() > 20) {
                    isPwdValid = false;
                    ct.addMessage("", new FacesMessage("Password must be of 6-20 characters"));
                } else {
                    if (!newPwdConfirm.equals(newPwd)) {
                        isPwdValid = false;
                        ct.addMessage("", new FacesMessage("Confirm password not correct"));
                    } else {
                        query = "update Users set Password='" + getNewPwd() + "' where UserID='" + Integer.parseInt(id) + "'";
                        st.executeUpdate(query);
                        st.close();
                        res.close();
                        ct.addMessage("", new FacesMessage("Password change successfull!"));
                    }
                }
            } else {
                ct.addMessage("", new FacesMessage("Current Password not correct !"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            ct.addMessage("", new FacesMessage("Cannot Change Password!"));
        }
        return "";

    }

    public String prepareData4Delete() {
        try {
            FacesContext ct = FacesContext.getCurrentInstance();
            Map<String, String> map = ct.getExternalContext().getRequestParameterMap();
            String id = map.get("idParam");
            users = usersDao.getObject(conn, Integer.parseInt(id));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "userDel";
    }
}
